/*
# File    :   transHex2Bin.cpp （把HEX文件转换为二进制）
# Author  :   Schips
# Ref     :   https://www.zhihu.com/question/41999778
# Mail    :   schips@dingtalk.com
# Date    :   2021-12-29
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_LINE 50
#define OUPUT "out.bin"

int transHexFile2Bin(char *filePath)
{
    char buf[MAX_LINE];		//缓冲区
    char fir[4];
    FILE *fp;			//文件指针
    int len, flag, i;			//行字符个数
    const char* output = OUPUT;
    ssize_t wr_size;
    int fd_w = open(output, O_WRONLY|O_CREAT|O_TRUNC,
                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
    if((fp = fopen(filePath,"r")) == NULL)
    {
        perror("Error Fail To Read");
        exit (1);
    }

    while(fgets(buf,MAX_LINE,fp) != NULL)
    {
        len = strlen(buf);
        if (len < 21)
        {
            //基本所有长度小于21的短行都是数据记录标记
            continue;
        }
        buf[len-1] = '\0';		//去掉换行符
        for (i = 9; i < len-3; i+=2)
        {
            //前八个字符是数据记录标志
            fir[0] = buf[i];
            fir[1] = buf[i+1];
            fir[3] = '\n';
            sscanf(fir,"%x",&flag);
            wr_size = write(fd_w, (const char*)&flag, 1);
        }
    }
    close(fd_w);
    fclose(fp);
    return 0;
}

int main(int argc, char *argv[])
{
    if(argc < 1)
    {
        printf("Requied : [xx.hex]\n");
        return 1;
    }
    printf("<-- %s\n", argv[1]);
    if(transHexFile2Bin(argv[1]))
    {
        perror("Error Trans Hex to Bin.");
        exit(1);
    }
    printf("--> %s\n", OUPUT);

    return 0;
}

